<template>
  <div class="home">
    <div
      :style="{
        position: 'fixed',
        width: '100%',
        height: '100%',
        filter: 'blur(50px) brightness(60%)',
        backgroundColor: 'rgba(0,0,0,.5)',
        backgroundImage: `url(${bgcImg})`,

        zIndex: -1,
      }"
    ></div>
    <NavPlay />
    <div
      class="home__container"
      :style="`padding-bottom: ${HOMEBP ? '120px' : '0'}`"
    >
      <transition name="route">
        <keep-alive>
          <router-view />
        </keep-alive>
      </transition>
    </div>
    <audio
      ref="audio"
      :src="audioSrc"
      @timeupdate="onTimeUpdate"
      @canplay="getDuration()"
      preload="metadata"
    ></audio>
    <PlayList v-if="!IsShowFooter" />
    <!-- 音频普  音频可视化 -->
    <div class="Brief__container__Visualization" ref="Canvas_Brief">
      <canvas
        id="wrap"
        :height="`${CanvasHeight}px`"
        :width="`${CanvasWidth / 2}px`"
        :style="`left: calc(50% - ${CanvasWidth / 4}px);`"
        v-show="SpectrumBool && IsShowFooter"
      ></canvas>
    </div>
  </div>
</template>

<script>
import PlayList from "../views/footer/PlayList.vue";
import NavPlay from "../views/side/NavPlay.vue";

import BriefHome from "./footer/briefHome.vue";
import PlayListCopy from "./footer/PlayListCopy.vue";

import {
  getURLInfo,
  getMusicDetailInfo,
  getDefaultDetailId,
} from "@/Api/seachApi";

export default {
  name: "Home",
  components: {
    PlayList,
    NavPlay,
    // MainPlay,
    // Lyric,
    // RankingList,
    // InformationDetails,

    BriefHome,
    PlayListCopy,
  },
  data() {
    return {
      bgstyle: "",
      CanvasHeight: 400,
      CanvasWidth: 1000,
    };
  },
  computed: {
    // 获取audio路径
    audioSrc() {
      return this.$store.state.musicState.audioSrc;
    },
    isShowSeach() {
      return this.$store.state.musicState.isShowSeach;
    },
    IsShowFooter() {
      return this.$store.state.Routes.IsShowFooter;
    },
    // 音乐Id
    musicID() {
      return this.$store.state.musicState.musicID;
    },
    isClickPlay() {
      return this.$store.state.musicState.isClickPlay;
    },
    //   单首歌曲列表详情
    oneMusicPlayData() {
      return this.$store.state.musicState.oneMusicPlayData;
    },
    //首页的底部padding值
    HOMEBP() {
      return this.$store.state.PlayState.homeBottomPadding;
    },
    // 是否显示歌词
    // isShowLyric() {
    //   // console.log(isClickPlay)
    //   return await this.$store.state.musicState.isShowLyric;
    // },
    // 是否显示榜单页面
    // isShowRecoment() {
    //   return this.$store.state.musicState.isShowRecoment;
    // },
    // // 是否显示推荐页面
    // isRankingList() {
    //   return this.$store.state.musicState.isRankingList;
    // },
    // // 是否显示歌单详情列表
    // isCheakInfomate() {
    //   return this.$store.state.musicState.isCheakInfomate;
    // },
    bgcImg() {
      return this.$store.state.musicState.bgcImg;
    },
    // 歌曲播放顺序
    LoopPlayOrder() {
      return this.$store.state.musicState.LoopPlayOrder;
    },
    // 音频可视化是否显示
    SpectrumBool() {
      return this.$store.state.PlayState.SpectrumBool;
    },
  },
  created() {
    this.$nextTick(() => {
      // 获取audio 标签
      this.$store.commit("musicState/initAudio", this.$refs.audio);
    });
    this.getDetailId();
    // this.getToken();
  },
  mounted() {
    let that = this;
    this.CanvasWidth = this.$refs.Canvas_Brief.offsetWidth;
    window.addEventListener("resize", function () {
      that.$nextTick(() => {
        that.CanvasWidth = that.$refs.Canvas_Brief.offsetWidth;
      });
    });
  },
  methods: {
    // 判断是否有登录
    getToken() {
      this.axios({
        method: "GET",
        url: "https://autumnfish.cn/login/refresh",
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
      let userID = localStorage.getItem("musicUserID");
      if (userID == undefined) {
        console.log("userID");
      }
    },
    // 获取默认歌曲的Id
    async getDetailId() {
      await getDefaultDetailId()
        .then((res) => {
          let random = Math.round(Math.random() * 10);
          let musicId = res.result[random].id; // "2033842511"//
          this.$store.commit("musicState/SetMusicID", musicId);
          this.$store.commit(
            "musicState/SetMusicPlayListData",
            res.result[random].id
          );
          this.$store.commit(
            "musicState/SetMusicPlayListData",
            res.result[random].id
          );
          // 加入播放列表
          this.$store.commit("musicState/SetMusicPlayListData", musicId);
          this.getDefaultMusic(musicId);
          this.getMusicLyric();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 默认获取的歌曲
    async getDefaultMusic(id) {
      await getMusicDetailInfo(id)
        .then((res) => {
          this.$store.commit("musicState/OneMusicPlayData", res.songs);
          this.setbackGroundImg(res.songs[0]);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 传递歌曲url
    async getURL(id) {
      await getURLInfo({ id })
        .then((res) => {
          this.$store.commit("musicState/audioSrc", res.data[0].url);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getDuration() {
      // canplay时获取音频总时长
      // console.log("canplay时获取音频总时长", this.getAudioElement);
      this.$store.commit("musicState/getTagetTime", this.$refs.audio.duration);
    },

    // 监听audio播放
    onTimeUpdate(e) {
      // console.log("asdada",e);
      // // 获取播放进度条标签
      // let progress = this.$refs.proGress;
      // console.log("this.$refs.audio",this.$refs.audio);
      // console.log("返回音频播放的速度",this.$refs.audio.playbackRate);
      // console.log("音频已缓冲部分的 TimeRanges 对象",this.$refs.audio.buffered);
      // console.log("可用文本轨道的 TextTrackList 对象",this.$refs.audio.textTracks);
      // //获取音频当前播放时间
      let currentTime = this.$refs.audio.currentTime;
      // console.log(this.$refs.audio.currentTime);
      //获取音频播放总时间 duration
      // console.log(" this.getAudioElement",currentTime,"---",this.$refs.audio.duration);
      let tagetTime = this.$refs.audio.duration;
      // console.log(currentTime);
      this.$store.commit("musicState/getCurrentTime", currentTime);
      // this.getCurrentTime(currentTime);
      if (tagetTime + 1 > 1) {
        this.$store.commit("musicState/getTagetTime", tagetTime);
      }
      //  this.$store.commit("PlayState/SET_PAUSED", this.$refs.audio.paused);

      if (this.$refs.audio.ended) {
        this.$store.commit("PlayState/SET_ANIMATION_ROTALE", 0);
        this.$store.commit("musicState/isClickPlay", false);

        this.$store.commit("PlayState/SET_Is_Audio_Ended", true);
        // 播放完成时根据设置的播放顺序进行播放
        if (this.LoopPlayOrder === "2") {
          // 随机
          this.$store.dispatch("musicState/Set_RandomPlay");
        } else if (this.LoopPlayOrder === "1") {
          let timer = null;
          // 单曲
          this.$store.commit("PlayState/SET_Is_Audio_Ended", false);
          timer = setTimeout(() => {
            this.$store.commit("musicState/SetMusicID", this.musicID);
            this.$store.commit("musicState/isClickPlay", true);

            this.$refs.audio.play();
            clearTimeout(timer);
          }, 1500);
        } else {
          // 循环
          this.$store.dispatch("musicState/Get_Next_Player", this.musicID);
        }
        // setTimeout(() => {
        //   progress.style.width = 0;
        //   this.$refs.gressCircle.style.left = 0;
        //   this.autoPlayNext();
        // }, 300);
      }
    },
    // 设置背景图片
    setbackGroundImg(data) {
      if (data != undefined) {
        this.$store.commit("musicState/bgcImg", data.al.picUrl);
      }
    },
    // 获取的歌词
    getMusicLyric() {
      this.$store.dispatch("musicState/GET_MUSIC_LYRIC");
    },
    // 歌频谱
    spectrum() {
      let wrap = document.getElementById("wrap");
      let cxt = wrap.getContext("2d");
      //获取API
      // let AudioContext = AudioContext // || webkitAudioContext;
      let context = new AudioContext();
      //加载媒体
      let audio = this.$refs.audio;
      // console.log("歌频谱", audio);
      // console.log("歌频谱2", this.getAudioElement);
      //创建节点
      audio.crossOrigin = "anonymous"; //解決CORS跨域限制
      // autoplay-policy='no-user-gesture-required reverts'
      let source = context.createMediaElementSource(audio);

      var analyser = context.createAnalyser();
      //连接：source → analyser → destination
      source.connect(analyser);
      analyser.connect(context.destination);
      //创建数据
      let output = new Uint8Array(180);
      var step = Math.round(output.length / 60); //采样步长

      var H2 = 400; //高度
      var W2 = 4; //宽

      // 竖直频谱效果
      (function drawSpectrum() {
        analyser.getByteFrequencyData(output); //获取频域数据
        cxt.clearRect(0, 0, wrap.width, wrap.height);
        //画线条
        for (var p = 0; p < 100; p++) {
          var energy = (output[step * p] / 200.0) * 100;
          for (var t = 0; t < energy; t++) {
            // cxt2.beginPath();
            // cxt2.moveTo(16 * p + 3 + 10, H2 + W2 * t + 10);
            // cxt2.lineTo(16 * (p + 1) - 3, H2 + W2 * t);
            // cxt2.stroke();
            cxt.beginPath();
            cxt.moveTo(16 * p + 6, H2 - W2 * t);
            cxt.lineTo(16 * (p + 1) - 3, H2 - W2 * t);
            cxt.stroke();
          }
          var linearGradient = cxt.createLinearGradient(50, 50, 50, 420);
          linearGradient.addColorStop(0.1, "rgba(206, 180, 230,1)");
          linearGradient.addColorStop(0.3, "rgba(153, 130, 243,1)");
          linearGradient.addColorStop(0.4, "rgba(139, 122, 255,1)");
          linearGradient.addColorStop(0.5, "rgba(213, 159, 255,1)");
          linearGradient.addColorStop(0.7, "rgba(185, 184, 235,0.8)");
          linearGradient.addColorStop(0.85, "rgba(231, 197, 213,1)");
          linearGradient.addColorStop(0.99, "rgba(107, 213, 255,.7)");

          cxt.strokeStyle = linearGradient;
          // if (this.isClickPlay) {
          //   cxt2.beginPath();
          //   cxt2.moveTo(16 * p + 3, H2);
          //   cxt2.lineTo(16 * (p + 1) - 3, H2);
          //   cxt2.stroke();
          // }
        }
        cxt.fill();
        //请求下一帧
        requestAnimationFrame(drawSpectrum);
      })();
    },
  },

  // 阻止多次点击
  watch: {
    "$store.state.musicState.audioSrc": function (newVal) {
      if (this.$store.state.musicState.audioSrc == newVal) {
        return;
      }
    },
    musicID(newVal) {
      this.getDefaultMusic(newVal);
      this.getURL(newVal);
      this.getMusicLyric();
    },
    audioSrc() {
      this.$nextTick(() => {
        this.spectrum();
      });
    },
   
  },
};
</script>
<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  &__container {
    // position: absolute;
    // top: 0;
    // left: 0;
    width: 100%;
    height: 100%;
    transition: all 0.5s;
    box-sizing: border-box;
  }
}
// 音频可视化
.Brief__container__Visualization {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100vw;
  height: 100vh;
  // background-color: red;
  z-index: -1;

  canvas {
    position: absolute;
    bottom: 0px;
  }
}
</style>
